import CryptoJS from 'crypto-js';

const CryptoSecret = '__CryptoJS_Secret__';

const key = CryptoJS.enc.Utf8.parse('abcdefgabcdefg12'); // 十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('3db83091ce5bcc41'); // 十六位十六进制数作为密钥偏移量
const mode = {
  iv,
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7
};

/**
 * 自定义加密数据
 * @param data - 数据
 */
export function customEncrypto(data: any) {
  const srcs = CryptoJS.enc.Utf8.parse(data);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, mode);
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * 自定义解密数据
 * @param cipherText - 密文
 */
export function customDecrypto(cipherText: string) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(cipherText);
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const decrypt = CryptoJS.AES.decrypt(srcs, key, mode);
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

/**
 * 加密数据
 * @param data - 数据
 */
export function encrypto(data: any) {
  const newData = JSON.stringify(data);
  return CryptoJS.AES.encrypt(newData, CryptoSecret).toString();
}

/**
 * 解密数据
 * @param cipherText - 密文
 */
export function decrypto(cipherText: string) {
  const bytes = CryptoJS.AES.decrypt(cipherText, CryptoSecret);
  const originalText = bytes.toString(CryptoJS.enc.Utf8);
  if (originalText) {
    return JSON.parse(originalText);
  }
  return null;
}
